package com.shopping.jwt;

import com.shopping.utils.RSAUtils;
import io.jsonwebtoken.*;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTTokenBaseRSA {


    //签发:生成一个Token
    public static String createToken() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
        //读取公钥
        PublicKey publicKey = RSAUtils.getPublicKey("D:\\Java源码\\demo\\shopping\\myshopping-project-server\\src\\main\\resources\\Keys\\key.public");
        //读取私钥
//        PrivateKey privateKey = RsaUtils.getPrivateKey("D:\\Java源码\\demo\\shopping\\myshopping-project-server\\src\\main\\resources\\Keys\\key.private");
        //标头map集合
        Map<String, Object> heardMap = new HashMap<String, Object>() {{
            put("typ", "JWT");
            put("alg", "HS256");//设置签名算法
        }};
        //负载信息map集合
        Map<String, Object> payloadMap = new HashMap<String, Object>() {{
            put("user_id", 93);
            put("user_name", "admin");
            //下方为jwt提供的标准自段
            put("iss", "huozhexiao");//签发人
            put("exp", new Date(System.currentTimeMillis() + (1000 * 60 * 60 * 24 * 7)));//过期时间
            put("iat", new Date());//签发时间
            put("sub", "JWT测试");//主题
            put("jti", "huozhexiao001");//编号
        }};
        String token = Jwts.builder()//创建一个JWT构建器对象
                .setHeader(heardMap)//设置标头，可以不设置，有默认值
                .setClaims(payloadMap)//设置负载信息
//                .signWith(privateKey//设置秘钥
//                        , SignatureAlgorithm.HS256 //签名算法
//                )
                .signWith(publicKey)//设置签名使用私钥生成
                .compact();//生成Token
        ;
        //生成Token
        return token;
    }

    /**
     * 解析Token
     * 解析时，必须提供秘钥和token字符串
     *
     * @param token
     */
    public static void parseToken(String token) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
        //读取公钥
        PublicKey publicKey = RSAUtils.getPublicKey("D:\\Java源码\\demo\\shopping\\myshopping-project-server\\src\\main\\resources\\Keys\\key.public");
        //读取私钥
        PrivateKey privateKey = RSAUtils.getPrivateKey("D:\\Java源码\\demo\\shopping\\myshopping-project-server\\src\\main\\resources\\Keys\\key.private");
        //解析指定Token并返回数据
        Jws<Claims> claimsJws = Jwts.parserBuilder()//创建一个解析构建器对象
//                .setSigningKey(Keys.hmacShaKeyFor(secretKet.getBytes(StandardCharsets.UTF_8)))//设置解析器所使用的秘钥
//                .setSigningKey(privateKey)//私钥来解签
                .setSigningKey(publicKey)//公钥来解签
                .build()//获得Token解析器对象
                .parseClaimsJws(token);
        ;
        System.out.println(claimsJws.getSignature());//获得签名
        JwsHeader header = claimsJws.getHeader();//获得标头对象
        System.out.println(header.getAlgorithm());//获得签名算法
        //获得负载数据对象
        Claims claims = claimsJws.getBody();
        System.out.println(claims.getSubject());//主题
        System.out.println(claims.getIssuer());//签发人
        System.out.println(claims.getExpiration());//过期时间
        System.out.println(claims.getIssuedAt());//签发时间
        System.out.println(claims.getId());//编号
        System.out.println(claims.get("user_id", Integer.class));
        System.out.println(claims.get("user_name", String.class));
    }

    public static void main(String[] args) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
        System.out.println(createToken());
//        parseToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJKV1TmtYvor5UiLCJ1c2VyX2lkIjo5MywidXNlcl9uYW1lIjoiYWRtaW4iLCJpc3MiOiJodW96aGV4aWFvIiwiZXhwIjoxNjgwODQ0Mzk4LCJpYXQiOjE2ODAyMzk1OTgsImp0aSI6Imh1b3poZXhpYW8wMDEifQ.sQYka7mRHhIm4h7PRbW-TWou8KvLCnwtb8E-LzKPHhy4oFqh9_z7hMD-XV_phadjiI8It9cpFYBnH8TQFuNwfpGF8l8vd64eX5n1e3joh24ocq5HkS9lr2nLFT4zkX3U01jtcS60mA089tXuwhnkd6dqr0T01PfYy1LGMiyUUDNZJgWIFGZEQpyQ3KwcVUMvplhvFL20ebDko3lBkdZOkullH0l0oEDBSDSKnLaNZJhaZ_iOpq3aJGalmWdEv8AyqrnfrUpOD_By136IYtdbtk0uChF6eonDi9avW-XH4KIb7js-HhRP4plwrRmzOH4Wrrc29wcYla_UY8Tk8jrEqA"
//        );
    }
}
